import 'package:flutter/material.dart';
import 'package:flutter_rider/event/click_operators_event.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main/models/operator_model.dart';

import '../../../module/task/provider/task_operator_provider.dart';

class PopOperatorUserList extends  ConsumerStatefulWidget {
  //type 1:装货 2:卸货
  int type = 1;
  String ? name;
  String ? mobile;
  int ? id;
  List ? chooseList;
  PopOperatorUserList(this.type, {this.name,this.mobile,this.id,this.chooseList, Key? key}) : super(key: key);

  @override
  ConsumerState createState() => _PopOperatorUserListState();
}

class _PopOperatorUserListState extends  ConsumerState<PopOperatorUserList> {
  final _inputController = TextEditingController(text: "");
  List<OperatorModel> _data = [];
  List<OperatorModel> _result = [];
  List _chooseList = [];

  @override
  void initState() {
    super.initState();
    /// 从装卸货界面重新打开，要回显之前的选择操作人
    if(widget.chooseList!=null) {
      List arr =widget.chooseList ?? [];
      if(arr.isNotEmpty){
        _chooseList = arr.sublist(1);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: MediaQuery.of(context).padding.left, right: MediaQuery.of(context).padding.right),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(8.rpx)),
      ),
      child: Column(
        children: [
          8.hspace,
          _renderTitle(),
          _chooseList.isEmpty?0.wspace:_renderChoose(),
          4.hspace,
          _renderInput(),
          16.hspace,
          Expanded(
            child: StateLayout(
              dataCallback: _onDataCallback,
              url: "/waybill_mission/loader_list?page_size=1000",
              childBuilder: _renderContent,
            ),
          ),
        ],
      ),
    );
  }

  Widget _renderTitle() {
    return Container(
        height: 70.rpx,
        alignment: Alignment.center,
        child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              16.wspace,
              InkWell(
                child: SvgPicture.asset(R.image_left, width: 24.rpx, height: 24.rpx),
                onTap: _backClick,
              ),
              4.wspace,
              Expanded(
                  child: Container(
                    alignment: Alignment.center,
                    child: UText.get("选择${widget.type == 1?'装货':'卸货'}人", Colors.black, 20.rpx,fw: FontWeight.bold),
                  )),
              4.wspace,
              InkWell(
                child: UText.get("确定", UIColor.color_primary, 16.rpx),
                onTap: () {
                  // ref.read(taskOperatorProvider.state).state = _chooseList;
                  eventBus.fire(ClickOperatorsEvent(_chooseList));
                  Navigator.of(context).pop();
                },
              ),
              16.wspace,
            ])
    );
  }

  Widget _renderChoose() {
    return Container(
        width: double.infinity,
        margin: EdgeInsets.only(left:4.rpx, right: 16.rpx),
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        child:Column (
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Wrap(
              children: _chooseList.asMap().keys.map((index) => _renderOne(index)).toList(),
            ),
          ]
        )
    );
  }

  Widget _renderOne(int index) {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.rpx, vertical: 4.rpx),
        margin: EdgeInsets.only(left:12.rpx, right: 8.rpx,bottom:12.rpx),
        // constraints: const BoxConstraints(
        //     maxHeight: 82,
        // ),
        decoration: BoxDecoration(
            color: UIColor.color_content,
            border: Border.all(width: 1.rpx,color: const Color(0xffE7E7E7)),
            borderRadius: const BorderRadius.all(Radius.circular(20.0))
        ),
        child: GestureDetector(
            onTap: () {
              if(index > 0){
                setState(() {
                  _chooseList.removeAt(index);
                });
                check();
              }
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
              LimitedBox(
                maxWidth: 130,
                child:Text(_chooseList[index].name, style: TextStyle(color: UIColor.color_t13,fontSize: 14.rpx,),overflow: TextOverflow.ellipsis,maxLines: 1),
                  // UText.get(_chooseList[index].name, UIColor.color_t13, 14.rpx, textAlign: TextAlign.center),
              ),
                index == 0?0.wspace: Row(
                  children: [
                    8.wspace,
                    Icon(
                      Icons.close,
                      color: UIColor.color_t8,
                      size: 16.rpx,
                    )
                  ],
                )
              ],
            )
        )
    );
  }

  check() {
    print(_result);
    print(_chooseList);
    for(var i= 0;i<_result.length;i++) {
      /// 初始化为false
      _result[i].isCheck = false;
      for(var j= 0;j<_chooseList.length;j++) {
        if(_result[i].id == _chooseList[j].id) {
          _result[i].isCheck = true;
        }
      }
    }
    print(_result);
  }

  void _backClick() {
    Navigator.of(context).pop();
    // Navigator.pop(context);
  }

  Widget _renderInput() {
    return Container(
        color: UIColor.color_content,
        padding: EdgeInsets.only(
          left: 16.rpx,
        ),
        child:Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: TextField(
                  onChanged: _onTextChange,
                  controller: _inputController,
                  textInputAction: TextInputAction.done,
                  maxLength: 20,
                  decoration: InputDecoration(
                    constraints: BoxConstraints(minHeight: 44.rpx, maxHeight: 44.rpx),
                    counterText: "",
                    contentPadding: EdgeInsets.symmetric(vertical: 12.rpx, horizontal: 12.rpx),
                    isCollapsed: true,
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(
                          20.rpx,
                        ),
                        borderSide: BorderSide.none),
                    prefixIcon: Padding(
                      padding: EdgeInsets.only(left: 12.rpx, right: 4.rpx),
                      child: Icon(
                        Icons.search,
                        size: 20.rpx,
                        color: Colors.black.withOpacity(0.4),
                      ),
                    ),
                    prefixIconConstraints: BoxConstraints(maxHeight: 16.rpx),
                    hintText: "搜索姓名、电话",
                    hintStyle: TextStyle(color: const Color(0x66000000).withOpacity(0.4)),
                    filled: true,
                    fillColor: UIColor.color_input,
                    suffixIconConstraints: BoxConstraints(maxHeight: 16.rpx),
                    suffixIcon: _inputController.text.isNotEmpty? Container(
                      padding: EdgeInsets.only(right: 13.rpx),
                      child: GestureDetector(
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(150),
                            color: UIColor.color_t7,
                          ),
                          child: Icon(
                            Icons.close,
                            color: UIColor.color_content,
                            size: 16.rpx,
                          ),
                        ),
                        onTap: () {
                          _inputController.text = "";
                          _onTextChange("");
                        },
                      ),
                    ) : null,
                  ),
                ),
              ),
              16.wspace,
              _inputController.text.isNotEmpty?GestureDetector(
                  onTap: () {
                    _inputController.text = "";
                    _onTextChange("");
                  },
                  child: Row(
                    children: [
                      UText.get("取消", UIColor.color_primary, 16.rpx),
                      16.wspace
                    ],
                  )
              ):0.wspace,

            ]
        )
    );
  }

  _onTextChange(String text) {
    if (text.isEmpty) {
      setState(() {
        _result.clear();
        _result.addAll(_data);
      });
    } else {
      _result.clear();
      print(_data.length);

      for (int i = 0; i < _data.length; i++) {
        var name = _data[i].name;
        name = name.toLowerCase();
        var mobile = _data[i].mobile;
        if (name.contains(text) || mobile.contains(text)) {
          _data[i].title1 = _data[i].name.indexOf(_inputController.text) ==-1?_data[i].name:_data[i].name.indexOf(_inputController.text) ==0?'':_data[i].name.substring (0,_data[i].name.indexOf(_inputController.text));
          _data[i].title2 = _data[i].name.indexOf(_inputController.text) ==-1?'':_inputController.text;
          _data[i].title3 = _data[i].name.indexOf(_inputController.text) ==-1?'':_data[i].name.substring(_data[i].name.indexOf(_inputController.text)+_inputController.text.length);
          _data[i].title4 = _data[i].mobile.indexOf(_inputController.text) ==-1?_data[i].mobile:_data[i].mobile.indexOf(_inputController.text) ==0?'':_data[i].mobile.substring (0,_data[i].mobile.indexOf(_inputController.text));
          _data[i].title5 = _data[i].mobile.indexOf(_inputController.text) ==-1?'':_inputController.text;
          _data[i].title6 = _data[i].mobile.indexOf(_inputController.text) ==-1?'':_data[i].mobile.substring(_data[i].mobile.indexOf(_inputController.text)+_inputController.text.length);
          for(var element in _chooseList) {
            if(element.id == _data[i].id) {
              _data[i].isCheck = true;
            }
          }
          _result.add(_data[i]);
        }
      }
      // 不能删除
      setState(() {

      });
    }
  }

  _onDataCallback(dynamic data) {
    List list = [];
    list.insert(0,{"id":widget.id,"name":widget.name,"mobile":widget.mobile,"isCheck":true,"isDefault":true,"title1":'',"title2":'',"title3":'',"title4":'',"title5":'',"title6":''});
    _chooseList.insert(0,OperatorModel.fromMap({"id":widget.id,"name":widget.name,"mobile":widget.mobile,"isCheck":true,"isDefault":true,"title1":'',"title2":'',"title3":'',"title4":'',"title5":'',"title6":''}));
    for (var element in data) {
      list.add({...element,"isCheck": false,"isDefault":false,"title1":'',"title2":'',"title3":'',"title4":'',"title5":'',"title6":''});
    }
    for (var element in list) {
      _data.add(OperatorModel.fromMap(element));
      _result.add(OperatorModel.fromMap(element));
    }
    /// 获取选中的操作人列表
    _getChooseList();
    /// 回显选中的操作人
    check();
  }

  _getChooseList() {
    List list = [];
    print(_chooseList);
    for(var i =0;i<_chooseList.length;i++) {
      if(_chooseList[i].isCheck ) {
        list.add(_chooseList[i]);
      }
    };
    setState(() {
      _chooseList = list;
    });
  }

  Widget _renderContent(dynamic data) {
    if (_result.isEmpty) {
      return Center(
        child: UText.getSubText("暂无数据内容"),
      );
    }
    return ListView.separated(
      itemBuilder: _renderItem,
      itemCount: _result.length,
      separatorBuilder: _renderSeparator,
    );
  }

  Widget _renderSeparator(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
      height: 0.5.rpx,
      color: const Color(0xffE7E7E7),
    );
  }

  Widget _renderItem(BuildContext context, int index) {
    var item = _result[index];
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: SizedBox(
        width: double.infinity,
        height: 64.rpx,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            24.wspace,
            SizedBox(
              width: 100.rpx,
              child: _inputController.text.isNotEmpty?
              RichText(
                text: TextSpan(
                  text: item.title1,
                  style: TextStyle(
                      color: UIColor.color_t1,
                      fontSize: 16.rpx,
                      //fontWeight:FontWeight.w600
                  ),
                  children: [
                    TextSpan(text: item.title2, style:  TextStyle(color: UIColor.color_primary,fontSize: 16.rpx)),
                    TextSpan(text: item.title3, style:  TextStyle(color: UIColor.color_t1,fontSize: 16.rpx)),
                  ],
                ),
              ):Text(item.name, style: TextStyle(color:Colors.black,fontSize: 16.rpx,),overflow: TextOverflow.ellipsis,maxLines: 2),
            ),
            // UText.get(item.mobile.substring(0,3) + " " + item.mobile.substring(3,7) + " " + item.mobile.substring(7) , Colors.black, 16.rpx),
             _inputController.text.isNotEmpty?
            RichText(
              text: TextSpan(
                text: item.title4,
                style: TextStyle(
                  color: UIColor.color_t1,
                  fontSize: 16.rpx,
                  //fontWeight:FontWeight.w600
                ),
                children: [
                  TextSpan(text: item.title5, style:  TextStyle(color: UIColor.color_primary,fontSize: 16.rpx)),
                  TextSpan(text: item.title6, style:  TextStyle(color: UIColor.color_t1,fontSize: 16.rpx)),
                ],
              ),
            ):Text(item.mobile, style: TextStyle(color:Colors.black,fontSize: 16.rpx,),overflow: TextOverflow.ellipsis,maxLines: 2),

            const Spacer(),
            SvgPicture.asset(item.isDefault?R.image_unselect:item.isCheck?R.image_select:R.image_circle, width: 24.rpx, height: 24.rpx),
            24.wspace
          ],
        ),
      ),
      onTap: () {
        if(item.id != widget.id) {
         int index = 0;
         for(var i=0;i<_chooseList.length;i++){
           if(_chooseList[i].id == item.id ) {
             index = i;
           }
         }
         if(index>0){
          _chooseList.removeAt(index);
         }
         // print( _chooseList.indexOf(item.name));
         item.isCheck = !item.isCheck;
         _chooseList.add(item);
        }
        _getChooseList();
      },
    );
  }
}